﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Linq;
using 用户管理系统.Properties;
using static 用户管理系统.MyPrint;

namespace 用户管理系统
{
    public partial class Main : Form
    {
        public ConfigInfo configInfo;

        private Size windowSize = new Size(1280, 900);
        private Point firstControl = new Point(15, 10);
        private List<UserData> allUserDatas = new List<UserData>();
        private readonly MyLog myLog=new MyLog();
        private readonly Dictionary<string, int> colInfos = new Dictionary<string, int>()
        {
            { "编号",110 },
            { "用户名称",300 },
            { "购买日期",120 },
            { "联系电话",200 },
            { "销售人员",120 },
            { "装机人员",120 },
            { "详细地址",300 },
            { "金额",120 },
        };
        //private readonly string strFilter = null,strSort = "编号 Asc";
        //private readonly DataTable dataTable = new DataTable();
        //private bool isGetData = false;

        public Main()
        {
            InitializeComponent();
            GetConfig();
            InitWindow();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //txt_QValue.Text = "A2023000";
        }

        private void GetConfig()
        {

            try
            {
                MyJson myJson = new MyJson();
                FileInfo configFile = new FileInfo(Path.Combine(Application.StartupPath, "Config.json"));
                string json;
                if (configFile.Exists)
                {
                    if (!LoadConfig())
                    {
                        MessageBox.Show("配置文件加载失败，点击确定后将重新创建！", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                        if (!CreateConfig())
                        {
                            MessageBox.Show("配置文件创建失败，请检查后重试！", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                            System.Environment.Exit(0);
                        }
                    }
                }
                else
                {
                    if (!CreateConfig())
                    {
                        MessageBox.Show("配置文件创建失败，请检查后重试！", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                        System.Environment.Exit(0);
                    }
                }

                bool LoadConfig()
                {
                    try
                    {
                        json = File.ReadAllText(configFile.FullName);
                        configInfo = new ConfigInfo();
                        //configInfo = myJson.DeserializeObject<ConfigInfo>(json);
                        Dictionary<string, object> configs = myJson.DeserializeObject<Dictionary<string,object>>(json);
                        configInfo.MyServer = myJson.DeserializeObject<MyServer>(configs["MyServer"].ToString());
                        configInfo.MyPrintInfo = myJson.DeserializeObject<MyPrintInfo>(configs["MyPrintInfo"].ToString());
                        configInfo.MyColors = new MyColors();
                        configInfo.MyDgv = new MyDgv();
                        if (configInfo != null)
                        {
                            return true;
                        }
                        else
                        {
                            return false;
                        }
                    }
                    catch (Exception ex)
                    {
                        myLog.FileWriteLine(myLog.ERROR_DATE,ex.ToString());
                        return false;
                    }
                }

                bool CreateConfig()
                {
                    try
                    {
                        configInfo = new ConfigInfo();
                        ConfigInfo cfgInfo = new ConfigInfo
                        {
                            MyColors = null,
                            MyDgv = null
                        };
                        json = myJson.SerializeObject(cfgInfo);
                        using (StreamWriter sw = configFile.CreateText())
                        {
                            sw.WriteLine(json);
                        };
                        //File.WriteAllText(configFile.FullName, json);
                        return true;
                    }
                    catch (Exception ex)
                    {
                        myLog.FileWriteLine(myLog.ERROR, ex.ToString());
                        return false;
                    }
                }
            }
            catch (Exception)
            {

            }


        }

        /// <summary>
        /// 初始化窗口
        /// </summary>
        private void InitWindow()
        {
            this.Text = $"玉溪新天赋科技-{Application.ProductName} v{Application.ProductVersion}";
            this.Icon = Resources.UserManage;

            this.Size = windowSize;
            this.WindowState = FormWindowState.Maximized;

            cmb_SelectType.Items.AddRange(new object[] { "编号", "用户名称", "购买日期", "联系电话", "详细地址" });
            cmb_SelectType.Text = cmb_SelectType.Items[0].ToString();

            dtp_QValue.Location = txt_QValue.Location;
            dtp_QValue.Size = txt_QValue.Size;
            dtp_QValue.Visible = false;

            btn_Submit.Location = new Point(txt_QValue.Left + txt_QValue.Width + 15, txt_QValue.Top - 2);
            this.AcceptButton = btn_Submit;

            //this.cbo_Key.Location = new Point(15, 10);
            //this.cbo_Key.Width = 200;
            //this.btn_Add.Location = new Point(cbo_Key.Left + cbo_Key.Width + 10, cbo_Key.Top - 2);
            //this.btn_Delete.Location = new Point(btn_Add.Left + btn_Add.Width + 10, btn_Add.Top);
            //this.btn_Refresh.Location = new Point(btn_Delete.Left + btn_Delete.Width + 10, btn_Add.Top);

            //过滤器
            //lbl_Filter.Location = new Point(btn_Refresh.Width + btn_Refresh.Left + 20, cbo_Key.Top + 5);
            //cbo_ColName.Location = new Point(lbl_Filter.Width + lbl_Filter.Left + 5, cbo_Key.Top);
            //cbo_ColName.Width = 70;
            //cbo_ColName.Items.AddRange(strColNames.ToArray());
            //cbo_Compare.Location = new Point(cbo_ColName.Width + cbo_ColName.Left + 5, cbo_Key.Top);
            //cbo_Compare.Width = 110;
            //cbo_Compare.Items.AddRange(strCompare.ToArray());
            //tbx_Filter.Width = 180;
            //tbx_Filter.Location = new Point(cbo_Compare.Width + cbo_Compare.Left + 5, cbo_Key.Top - 1);
            //btn_Filter.Location = new Point(tbx_Filter.Width + tbx_Filter.Left + 5, btn_Add.Top);

            //提交按钮
            //this.btn_Submit.Location = new Point(Width - btn_Submit.Width - 30, btn_Add.Top);

            //dgvData位置
            this.dgvData.Location = new Point(firstControl.X, cmb_SelectType.Top + cmb_SelectType.Height + 15);

            //设置标题列样式
            this.dgvData.EnableHeadersVisualStyles = false;
            this.dgvData.ColumnHeadersDefaultCellStyle.ForeColor = configInfo.MyDgv.MainTableHeader.ForeColor;
            this.dgvData.ColumnHeadersDefaultCellStyle.BackColor = configInfo.MyDgv.MainTableHeader.BackColor;
            dgvData.ColumnHeadersDefaultCellStyle.Font = configInfo.MyDgv.MainTableHeader.Font;
            // 标题行高
            int rowHeight = MyClass.GetHeight(configInfo.MyDgv.MainTableText.Font.Height, 1.2);
            dgvData.RowTemplate.Height = rowHeight;

            //禁用行标题
            //this.dgvData.RowHeadersVisible = false;
            //禁用行标题大小调整
            this.dgvData.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.DisableResizing;
            //禁用列标题大小调整
            //this.dgvData.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
            //设置各表头各列文字居中
            this.dgvData.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            //设置隔行背景颜色
            //this.dgvData.AlternatingRowsDefaultCellStyle.BackColor = Color.LightGray;
            this.dgvData.AlternatingRowsDefaultCellStyle.BackColor = (Color)new ColorConverter().ConvertFrom("#F2F2F2");
            //禁止增加新行
            this.dgvData.AllowUserToAddRows = false;
            //禁用列排序
            //dgvData.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;

            // 禁止用户改变DataGridView的所有列的列宽   
            //dgvData.AllowUserToResizeColumns = false;

            //禁止用户改变DataGridView所有行的行高   
            dgvData.AllowUserToResizeRows = false;
            //禁止修改ID列
            //dgvData.Columns["ID"].ReadOnly = true;
            dgvData.RowHeadersWidth = 30;


            //表格字体
            this.dgvData.Font = configInfo.MyDgv.MainTableText.Font;
            this.dgvData.DefaultCellStyle.SelectionForeColor = configInfo.MyDgv.SelectText.ForeColor;
            this.dgvData.DefaultCellStyle.SelectionBackColor = configInfo.MyDgv.SelectText.BackColor;
            this.dgvData.DefaultCellStyle.ForeColor = configInfo.MyDgv.MainTableText.ForeColor;
            this.dgvData.DefaultCellStyle.BackColor = configInfo.MyDgv.MainTableText.BackColor;

            // 选择初始单元格
            //tbx_user.Select();
            //tbx_user.Focus();
            this.dgvData.Select();
            //this.dgvData.CurrentCell = dgvData[1, 0];


            //创建表
            InitDataTable();
        }

        /// <summary>
        /// 生成dgvData各列
        /// </summary>
        private void InitDataTable()
        {
            DataGridViewTextBoxColumn textColumn;
            int i = 0;
            string[] leftCols = { "用户名称", "详细地址" };

            foreach (var colInfo in colInfos)
            {
                textColumn = new DataGridViewTextBoxColumn
                {
                    ValueType = typeof(string),
                    HeaderText = colInfo.Key,
                    SortMode = DataGridViewColumnSortMode.NotSortable,
                    Width = colInfo.Value,
                    MinimumWidth = colInfo.Value,
                    Name = colInfo.Key,
                };
                if (leftCols.Contains(colInfo.Key))
                {
                    textColumn.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft;
                }
                else
                {
                    textColumn.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
                }
                dgvData.Columns.Add(textColumn);
                i++;
            }
            dgvData.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            dgvData.EditMode = DataGridViewEditMode.EditProgrammatically;
            dgvData.Rows.Add();
        }



        /// <summary>
        /// 获取数据写入Table，并执行筛选
        /// </summary>
        /// <param name="tabName"></param>
        /// <returns></returns>
        private void GetDateToTable(string qName, string qValue)
        {
            PostData postData = new PostData()
            {
                action = "Q",
                type = "用户资料",
                match = $"{qName} like '%{qValue}%'"
            };
            if (qName.Equals("购买日期"))
                postData.match = $"{qName} between '{qValue}' and '{qValue}'";

            //检查数据是否改变
            //if (DataChageQuestion()) return false;
            string urlFlag = "get_user";
            GetDatas(urlFlag, postData);
            //FilterData(dataTable, strFilter, strSort);
            SetStatus(true);
        }

        private void GetDatas(string urlFlag, PostData postData)
        {
            MyServer myServer = new MyServer();
            MyData myData = new MyData(myServer);
            ResUser resData = myData.QueryUser(urlFlag, postData);
            if (resData.code == 0)
            {
                allUserDatas = resData.datas;
            }
            else
            {
                allUserDatas = null;
            }
            UpdateDgvData(allUserDatas);
            UpdateStatus(resData.message);
        }

        /// <summary>
        /// dgvData过滤器
        /// </summary>
        /// <param name="dt">dt表</param>
        /// <param name="filter">过滤公式</param>
        /// <param name="sort">排序方式</param>
        //private void FilterData(DataTable dt, string filter, string sort)
        //{
        //    DataTable dt1 = dt.Copy();
        //    DataRow[] drs = dt1.Select(filter, sort);
        //    for (int i = 0; i < drs.Length; i++)
        //    {
        //        Console.WriteLine(drs[i][0]);
        //    }
        //    dataTable.Clear();
        //    foreach (DataRow item in drs)
        //    {
        //        dataTable.Rows.Add(item.ItemArray);
        //    }
        //    //dgvData.DataSource = dataTable;
        //    UpdateDgvData(drs);
        //}


        /// <summary>
        /// 设置dgvData表数据
        /// </summary>
        /// <param name="drs">DataRow行数组</param>
        public void UpdateDgvData(List<UserData> UserDatas)
        {
            if (InvokeRequired)
            {
                Invoke(new Action(() => UpdateDgvData(UserDatas)));
            }
            else
            {
                //清空数据表
                dgvData.Rows.Clear();
                //添加数据
                foreach (UserData userData in UserDatas)
                {
                    object[] row = new object[]
                    {
                        userData.编号,
                        userData.用户名称,
                        userData.购买日期.ToString("yyyy-MM-dd"),
                        userData.联系电话,
                        userData.销售人员,
                        userData.装机人员,
                        userData.详细地址,
                        userData.金额?.ToString("F2")
                    };
                    dgvData.Rows.Add(row);
                }

                //设置奇数行背景
                dgvData.AlternatingRowsDefaultCellStyle.BackColor = (Color)new ColorConverter().ConvertFrom("#F2F2F2");
            }
        }

        private void UpdateStatus(string text)
        {
            if (InvokeRequired)
            {
                Invoke(new Action(() => UpdateStatus(text)));
            }
            else
            {
                tssl_Status.Text = $"状态：{text}";
            }
        }

        private void btn_Submit_Click(object sender, EventArgs e)
        {

            string qName = cmb_SelectType.Text;
            string qValue;
            if (qName.Equals("购买日期"))
            {
                qValue = dtp_QValue.Value.ToString("yyyy-MM-dd");
            }
            else
            {
                qValue = txt_QValue.Text.Replace("*", "%");
            }
            if (!qName.Equals("购买日期") && (string)qValue == string.Empty)
            {
                MessageBox.Show("查询信息不能为空！", $"{Application.ProductName}-查询错误", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            SetStatus(false);
            UpdateStatus("查询数据...");
            new Thread(new ThreadStart(() => GetDateToTable(qName, qValue))).Start();
            //Task.Run(() => GetDateToTable(qName, qValue));
        }

        private void dgvData_DoubleClick(object sender, EventArgs e)
        {
            UserManage f2 = new UserManage()
            {
                configInfo = configInfo,
                userData = allUserDatas.Count > 0 ? allUserDatas[dgvData.CurrentRow.Index] : null
            };
            f2.ShowDialog();
        }

        private void Form1_SizeChanged(object sender, EventArgs e)
        {
            if (this.Width < windowSize.Width)
            {
                this.Width = windowSize.Width;

            }
            else if (this.Height < windowSize.Height)
            {
                this.Height = windowSize.Height;
            }
            this.dgvData.Size = new Size(this.Width - firstControl.X * 2 - 20, this.Height - dgvData.Top - ssr_Main.Height - 50);

        }

        private void SetStatus(bool status)
        {
            if (InvokeRequired)
            {
                Invoke(new Action(() => SetStatus(status)));
            }
            else
            {
                btn_Submit.Enabled = status;
            }
        }


        private void cmb_SelectType_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmb_SelectType.Text.Equals("购买日期"))
            {
                dtp_QValue.Visible = true;
                txt_QValue.Visible = false;
            }
            else
            {
                dtp_QValue.Visible = false;
                txt_QValue.Visible = true;
            }
        }

        private void 数据同步ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DataSync sync = new DataSync
            {
                configInfo = configInfo
            };
            sync.ShowDialog();
        }

    }
}
